<template>
  <div id="chart" class="chart">
    <!-- <code class="pos-test" @click="test()">{{ sfb }}</code> -->
    <!-- <button @click="test()">btn</button> -->
  </div>
</template>
<script>
import { bus } from '@/main.js';
import { mapState, mapMutations } from 'vuex';

import { init, dispose } from 'klinecharts';
import { option } from './optsKLine.js';
let _configOpts = option;

export default {
  name: 'KlineChart',
  mixins: [], //混入
  components: {}, //组件
  props: {
    stockCode: {
      type: [String],
      validator: function(value) {
        let re = new RegExp(/^\d{4,6}\.[A-Z]{2,3}$/);
        return re.test(value);
      },
    },
  }, //集成属性
  data() {
    return {
      linedata: [],
      chart: null,
      sfb: null,
    };
  },
  computed: {
    ...mapState(['winSize', 'stock']),
    params_code: function() {
      let p = {
        get_type: 'range',
        prod_code: this.stockCode,
        candle_period: 6,
        // fields
        search_direction: 2,
        data_count: 300,
        // start_date: this.$moment()
        //   .subtract(1, 'years')
        //   .format('YYYYMMDD'),
        // end_date: this.$moment().format('YYYYMMDD'),
      };
      return p;
    },
  },
  methods: {
    ...mapMutations([]),
    test: function() {
      console.log('test');
      let st = this.chart.getStyles();
      console.log(st);
    },
    formatData: function(item) {
      let obj = {};
      return obj;
    }, //目前无用
    ajaxData: function() {
      let p = this.params_code;
      this.$api
        .getKline(p)
        .then((res) => {
          let key = p.prod_code;
          this.$store.commit(
            'stock/setHsDataFormatted',
            this._.get(res, 'data.candle')[key]
          );
          this.linedata.splice(0, this.linedata.length);
          this.linedata.push(...this.$store.getters['stock/getLineData']());
          return Promise.resolve(200);
        })
        .then((res) => {
          document.title = p.prod_code;
          this.chart.applyNewData(this.linedata);
        })
        .catch((err) => {
          console.error(err);
        })
        .finally((_) => {});
    },
  },
  beforeCreate: function() {},
  created: function() {},
  beforeMount: function() {},
  mounted: function() {
    this.chart = init('chart', _configOpts);
    this.ajaxData();
    // 订阅动作：
    // onDataReady：数据准备
    // onZoom：缩放
    // onScroll：滚动
    // onVisibleRangeChange：可视范围变化
    // onCrosshairChange：十字标变化
    // onTooltipIconClick：--
    // onPaneDrag：--
    this.chart.subscribeAction('onDataReady', (e) => {
      let a = this.chart.getVisibleRange();
      bus.$emit('datazoom', a);
    });
    this.chart.subscribeAction('onVisibleRangeChange', (e) => {
      // console.log(e);//e===this.chart.getVisibleRange();
      // form:number,数据左端，min0
      // realFrom:number,图表左端，可负值
      // to:number,数据右端，max
      // realTo:number,图表右端，可超值
      bus.$emit('datazoom', e);
      this.sfb = e;
    });
    this.chart.subscribeAction('onCrosshairChange', (e) => {});
    bus.$on('resizeWindow', () => {
      console.log('resizeWindow');
      this.chart.resize();
    });
  },
  beforeUpdate: function() {},
  updated: function() {},
  beforeDestroy: function() {},
  destroyed: function() {
    this.chart.subscribeAction('onZoom');
  },
};
</script>
<style lang="less" scoped>
.chart {
  height: 100%;
  width: 100%;
  background-color: rgb(17, 18, 25);
}
.pos-test {
  position: absolute;
  top: 0;
  right: 10px;
  background-color: black;
  color: white;
}
</style>
